package com.xiaobawang.hundouluo.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xiaobawang.hundouluo.R;
import com.xiaobawang.hundouluo.bean.Environment;
import com.xiaobawang.hundouluo.service.DataService;
import com.xiaobawang.hundouluo.utils.SharedPreferencesUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class EnvironmentFragment extends Fragment {

    private List<Environment> list;  //数据源
    private BaseAdapter adapter;  //适配器
    private GridView gv;  //控件

    public EnvironmentFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        readSetting();

        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_environment, container, false);
        //找出GridView
        gv = root.findViewById(R.id.fragment_environment_gv);

        //new出数据源
        list = new ArrayList<>();

        //new适配器
        adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return list.size();
            }

            @Override
            public Object getItem(int i) {
                return list.get(i);
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            //用来设置当前单元格所显示的数据，将数据绑定到控件上
            @Override
            public View getView(int i, View view, ViewGroup viewGroup) {
                //找出GridView的布局文件
                View v = LayoutInflater.from(EnvironmentFragment.this.getContext()).inflate(R.layout.gv_environment_item, null);
                LinearLayout linear = v.findViewById(R.id.gv_environment_item_linear_up);

                //找出item里的控件
                TextView tvStatus = v.findViewById(R.id.gv_environment_item_tv_status);
                TextView tvData = v.findViewById(R.id.gv_environment_item_tv_data);
                TextView tvUnit = v.findViewById(R.id.gv_environment_item_tv_unit);
                TextView tvName = v.findViewById(R.id.gv_environment_item_tv_name);

                //得到当前位置的数据
                Environment environment = list.get(i);

                //数据绑定控件
                tvStatus.setText(environment.getStatus());
                tvData.setText(environment.getData().toString());
                tvUnit.setText(environment.getUnit());
                tvName.setText(environment.getName());
                switch (environment.getName()) {
                    case "airTemp" : tvName.setText("空气温度"); break;
                    case "soilHum" : tvName.setText("土壤湿度"); break;
                    case "light" : tvName.setText("光照强度"); break;
                    case "CO2浓度" : tvName.setText("CO2浓度"); break;
                }

                //为不同的状态添加不同的背景色
                if("报警".equals(environment.getStatus())){
                    linear.setBackgroundResource(R.drawable.round_bg_red);
                    tvName.setTextColor(Color.RED);
                }

                return v;
            }
        };

        //GridView加载适配器
        gv.setAdapter(adapter);

        //注册广播接收器
        receiver =new DataReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.xiaobawang.hundouluo.receiver.data.realtime");
        EnvironmentFragment.this.getContext().registerReceiver(receiver, filter);

        //启动服务
        Intent sIntent = new Intent(EnvironmentFragment.this.getContext(), DataService.class);
        sIntent.putExtra("type", "realtime");
        EnvironmentFragment.this.getContext().startService(sIntent);

        return root;
    }

    BroadcastReceiver receiver;

    @Override
    public void onDestroy() {
        super.onDestroy();
        EnvironmentFragment.this.getContext().unregisterReceiver(receiver);
    }

    private void readSetting() {

        String airMin = SharedPreferencesUtil.read(EnvironmentFragment.this.getContext(), "airTemp", "min");
        String airMax = SharedPreferencesUtil.read(EnvironmentFragment.this.getContext(), "airTemp", "max");
        String soilMin = SharedPreferencesUtil.read(EnvironmentFragment.this.getContext(), "soilHum", "min");
        String soilMax = SharedPreferencesUtil.read(EnvironmentFragment.this.getContext(), "soilHum", "max");
        String carbonDioxideMin = SharedPreferencesUtil.read(EnvironmentFragment.this.getContext(), "carbonDioxide", "min");
        String carbonDioxideMax = SharedPreferencesUtil.read(EnvironmentFragment.this.getContext(), "carbonDioxide", "max");
        String illuminationMin = SharedPreferencesUtil.read(EnvironmentFragment.this.getContext(), "light", "min");
        String illuminationMax = SharedPreferencesUtil.read(EnvironmentFragment.this.getContext(), "light", "max");

        Log.e("EnvironmentDataInterval","airMin:" + airMin + "airMax" + airMax +
                "soilMin:" + soilMin + "soilMax" + soilMax +
                "carbonDioxideMin:" + carbonDioxideMin + "carbonDioxideMax" + carbonDioxideMax +
                "illuminationMin:" + illuminationMin + "illuminationMax" + illuminationMax);
    }

    class DataReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getStringExtra("status").equalsIgnoreCase("success")) {

                //更新数据源数据
                list = intent.getParcelableArrayListExtra("datas");

                //状态的处理
                for (Environment item : list) {
                    String min = SharedPreferencesUtil.read(EnvironmentFragment.this.getContext(), item.getName(), "min");
                    String max = SharedPreferencesUtil.read(EnvironmentFragment.this.getContext(), item.getName(), "max");
                    if (min == "false" || max == "false") {
                        Toast.makeText(EnvironmentFragment.this.getContext(), item.getName() + "未设置报警值!", Toast.LENGTH_LONG).show();
                        item.setStatus("正常");
                    } else {
                        double minD = Double.parseDouble(min);
                        double maxD = Double.parseDouble(max);
                        item.setStatus(item.getData() <= maxD && item.getData() >= minD ? "正常" : "报警");
                    }
                }

                //额外增加二氧化碳的数据
                list.add(new Environment("正常", 35.5, "Kix", "CO2浓度"));

                //GridView刷新程序
                adapter.notifyDataSetChanged();
            } else {
                Toast.makeText(EnvironmentFragment.this.getContext(), "获取数据失败!请稍后再试", Toast.LENGTH_LONG).show();
            }
        }
    }

}
